package cz.cvut.fel.riak.loader;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cz.cvut.fel.riak.stats.Statistics;

public class Main {
/*
 * 0. parametr cesta
 * 1. pocet iteraci
 * 2. parametr servery
 * 3. parametr pocet vlaken
 * 4. parametr velikost
 * 5. parameter batch size
 */
	final static Logger log = LoggerFactory.getLogger(Main.class);
	public static AtomicLong[] al = { new AtomicLong(100000000-1),  new AtomicLong(100000000)};;

	public static int remaining;
	
	public static void main(String[] args) throws IOException, InterruptedException {
		log.info("Start");
		Random r = new Random();
		
	/*	al[0].set(al[0].get()*Integer.parseInt(args[5]));
		al[1].set(al[1].get()*Integer.parseInt(args[5]));
		al[2].set(al[2].get()*Integer.parseInt(args[5]));*/
		
		
        byte[] value = new byte[Integer.valueOf(args[4])];
        r.nextBytes(value);
	    
        LoadJob.data =  value;
		LoadJob[] jobs = new LoadJob[Integer.parseInt(args[3])];
		String[] servers = args[2].split(","); 
		
		
		for (int i = 0; i < jobs.length; i++) {
			jobs[i] = new LoadJob(args[0], Long.parseLong(args[1]),servers[r.nextInt(servers.length)],Integer.parseInt(args[5]));
			jobs[i].add = (Integer.parseInt(args[5]) == 0 ? false : true);
			//jobs[i].number = al[Integer.parseInt(args[5])];
			
		}
		log.info("Loaded thread: "+jobs.length);
		
		for (int i = 0; i < jobs.length; i++) {
			jobs[i].start();
			remaining++;
		}
		
		long testStartTime = System.currentTimeMillis();
		long epoch = 0;
		int total = 0;
		long keyCount = 0;
		long latency = 0;
		int oldTotal;
		long oldLatency;
		long oldKeyCount = 0;
		
		while(remaining != 0) {
	       Thread.sleep(1000);
	        
	        epoch++;
	        
	        epoch = 0;

            oldTotal    = total;
            oldLatency  = latency;
            oldKeyCount = keyCount;

            Statistics stats = Statistics.getInstance(); 
            total    = stats.docs.get();
            //keyCount = sta.keys.get();
            latency  = stats.latency.get();

            int opDelta  = total - oldTotal;
           // int keyDelta = keyCount - oldKeyCount;
            double latencyDelta = latency - oldLatency;

            long currentTimeInSeconds = (System.currentTimeMillis() - testStartTime) / 1000;
            String formattedDelta = (opDelta > 0) ? Double.toString(latencyDelta / (opDelta * 1000)) : "NaN";

            System.out.println(String.format("%d,%d,%s,%d", total, opDelta, formattedDelta, currentTimeInSeconds) + ", -> Debug: min:"+al[0].get()+" max: "+al[1]);
		}
		
		
		for (int i = 0; i < jobs.length; i++) {
			jobs[i].join();
		}
		log.info("Stop");
		
	}

}
